package model;

import java.util.Comparator;
import java.util.PriorityQueue;

import org.apache.log4j.Logger;

public class Time {
	
	private static double time = 0.0;
	private static final Logger log = Logger.getLogger("Time");

	private static boolean active = true;
	
	public static double currentTime() {
		return time;
	}
	/*
	private static final String PATTERN = "%-5p %-25c{1} : %m%n";
	
	static {
		ConsoleAppender ca = new ConsoleAppender(new PatternLayout(PATTERN));
		ca.setThreshold(Level.INFO);
		BasicConfigurator.configure(ca);
	}
	*/
	private static PriorityQueue<Event> queue = new PriorityQueue<Event>(1024, new Comparator<Event>() {
		public int compare(Event o1, Event o2) {
			if (o1 == o2) {
				return 0;
			}
			return o1.getTime() <= o2.getTime() ? -1 : 1;
		}
	});

	public static void registerEvent(Event e) {
		if (time > e.getTime()) {
			log.fatal("time disrupture at " + e, new Exception());
		}
		log.debug("registering event " + e);
		queue.add(e);
	}
	
	public static boolean cancelEvent(Event e) {
		boolean wasThere = queue.remove(e);
		log.debug("cancelling event " + e + ": was in queue? " + wasThere);
		return wasThere;
	}
	
	@SuppressWarnings("unused")
	private static void printQueue() {
		String s = "Queue[";
		for (Event e : queue) {
			s += e + ", ";
		}
		log.debug((s.length() > 6 ? s.substring(0, s.length() - 2) : s) + "]");
	}

	public static void run() {
		log.info("beginning time flow at " + time);
		while(!queue.isEmpty() && active) {
			Event e = queue.poll();
			time = e.getTime();
			log.debug("performing " + e);
			e.perform();
		}
		log.info("ending time flow at " + time);
	}
	
	public static void stop() {
		active = false;
	}
	
}
